package com.ysd.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ysd.entity.Admin;

//Filter过滤器
public class LoginFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	// doFilter, 过滤的核心方法, 所有请求都会经过该方法
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request; // 将ServletRequest转化为HttpServletRequest
		HttpServletResponse res = (HttpServletResponse)response; //ServletResponse转化为HttpServletResponse
		
		String url = req.getRequestURI(); // 获得访问的路径

		HttpSession session = req.getSession(); // 创建session对象
		Admin admin = (Admin)session.getAttribute("admin"); // 从session中取出admin数据
		if(url.endsWith("login.html") || url.endsWith(".css") || url.endsWith(".js") || url.endsWith(".jpg")) {
			chain.doFilter(req, res); // 放行
		} else if (admin != null) { // 登陆过了
			chain.doFilter(req, res); // 放行
		} else { // 没有登陆过
			res.sendRedirect("login.html"); // 重定向到登陆页面
			//res.sendRedirect("/shangcheng/admin/login.html");
			// 绝对路径和相对路径
			// 绝对路径: 路径前有"/"代表绝对路径, 绝对路径是完整的路径
			// 相对路径: 路径前无"/"代表相对路径, 相对路径是相对于当前文件的路径
		}
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		
	}

}
